import { stringify } from 'querystring';
import { history } from 'umi';
import { fakeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const res = yield call(fakeAccountLogin, payload);
      if(res.status===200&&res.data.status==='ok'){
      let response={
        currentAuthority:res.data.data[0].roleId,
        status:res.data.status,
        type: "account",
        token:res.data.token
      }
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully

      if (response.status === 'ok') {
        sessionStorage.setItem('loginResult',JSON.stringify(response))
          history.replace( '/');
          window.location.reload("/#/welcome")
      }
      }
      else{
        message.error('用户名或密码错误',3)
      }
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
      window.location.href='/#/user/login'
      sessionStorage.clear()

      // if (window.location.pathname !== '/user/login' && !redirect) {
      //   history.replace({
      //     pathname: '/user/login',
      //     search: stringify({
      //       redirect: 'http://localhost:8000/#/user/login',
      //     }),
      //   });
      // }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
